// miniprogram/pages/my/register/index.js
var Mcaptcha = require('../../../utils/mcaptcha')
var Test = require('../../../utils/test')
import {UserModel} from '../../../model/user'
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '获取',
    time: 60, //倒计时时间
    isDisabled: false, // 按钮是否禁用
    timer: '', //定时器
    radio: '1',
    politicStatus: -1,
    phone:'',
    options: [{
      id: '0',
      name: '中共党员'
    }, {
      id: '1',
      name: '预备党员'
    },{
      id: '2',
      name: '入党积极分子'
    }, {
      id: '6',
      name: '流动党员'
    }, {
      id: '7',
      name: '无党派人士'
    },{
      id: '3',
      name: '共青团员'
    }, {
      id: '4',
      name: '群众'
    }, {
      id: '5',
      name: '其它'
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.mcaptcha = new Mcaptcha({
      el: 'canvas',
      width: 80,
      height: 35,
      createCodeImg: ""
    });
    this.test = new Test()
  },
  // 下拉框
  change(e){
    console.log(e)
    console.log(e.detail.id, e.detail.name)
    this.data.politicStatus = e.detail.id
  },
  // 单选框
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
  formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    if(this.data.politicStatus == -1){
      Toast('请选择政治面貌')
      return
    }
    // return
    this.reg(e.detail.value)
  },
  reg(data) {
    data.politicStatus = this.data.politicStatus
    data.openid=wx.getStorageSync('openid')
    console.log('注册传参',data)
    if(data.age > 28 && data.politicStatus == 3 ){
      Toast('共青团员年龄不得大于28')
      return
    }
    UserModel.phoneReg(data).then((res) => {
      if(res && res.code == 200) {
        // todo
        console.log('注册成功', res)
        wx.setStorageSync("isRegistered", res.data.isRegistered)
        wx.setStorageSync("user", res.data.user)
        wx.setStorageSync('session_key', res.data.session_key)
        wx.switchTab({
          url: '../index',
        })
      }else {
        console.log('注册失败',res)
        Toast(res.msg)
      }
    }).catch(e=> {
      console.log(e)
    })
  },
  getPhone(e){
    this.setData({
      phone: e.detail.value
    })
  },
  getSmsCode(){
    // console.log(1)
    if(!this.data.phone){
      Toast('手机号不得为空')
      return
    }
    // console.log(2)
    UserModel.sms(this.data.phone).then((res) => {
      if(res && res.code == 200) {
        Toast('验证码已发送')
        console.log('获取短信验证码', res)
        this.setData({
          isDisabled: true
        })
         //给定时器赋值
        this.data.timer = setInterval(() => {
          this.timer()
        }, 1000)
      }else {
        console.log('获取失败',res)
        Toast(res.msg)
      }
    }).catch(e=> {
      console.log(e)
    })
  },

  //定时器
 timer() {
   let time = this.data.time;
   time--;
   this.setData({
     time,
     title: time + 's'
   })
   //判断倒计时时间为0时
   if(time <= 0) {
     //清除定时器
     clearInterval(this.data.timer);
     //设置文本内容，倒计时间，按钮可用
     this.setData({
       title: '获取',
       time: 60,
       isDisabled: false
     })
   }
 },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  //刷新验证码
  onTap() {
    this.mcaptcha.refresh();
  },
  validateCode() {
    var res = this.mcaptcha.validate(this.data.imgCode);
    if (this.data.imgCode == '' || this.data.imgCode == null) {
      toast.showToast({
        title: '请输入验证码'
      })
      return;
    }
    if (!res) {
      toast.showToast({
        title: '验证码错误'
      })
      return;
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getPhoneNumber(e){
    console.log(e)
    if(e.detail.errMsg == 'getPhoneNumber:ok') {
      let data = {
        iv: e.detail.iv,
        encryptedData: e.detail.encryptedData,
        openId: wx.getStorageSync('openid')
      }
      this.loginStatus(data)
      
    }
  },
  loginStatus(data) {
    let that = this
    wx.checkSession({
      success: function () {
        console.log('存在登陆态')
        wx.login({
          success: res => {
            UserModel.getPhone(data).then(res => {
              console.log('获取手机号返回结果', res)
              that.setData({
                phone: res.data.purePhoneNumber
              })
            })
          },
          fail: function (err){
            console.log(err)
          }
        })
      },
      fail: function () {
        console.log('不存在登陆态')
        wx.login({
          timeout: 0,
          success: res => {
            UserModel.getPhone(data).then(res => {
              console.log('获取手机号返回结果', res)            
            })
          },
          fail: function (err){
            console.log(err)
          }
        })
      }
    })
  },
})